<template>
  <div style="padding: 32px; background: white">
    <a-space col="24">
      <a-input v-model:value="userName" placeholder="用户名"></a-input>
      <a-input v-model:value="realName" placeholder="真实姓名">真实姓名</a-input>

      <a-button @click="resetSearch">重置</a-button>
      <a-button type="primary" class="mr10" @click="search">搜索</a-button>
    </a-space>
    <a-space style="margin-bottom: 16px">
      <a-button type="primary" @click="add"> 新增 </a-button>

      <template v-if="selectedKeys.length !== 0">
        <a-button type="danger" @click="batchRemoveUser">删除</a-button>

        <a-button @click="batchSetManager">设置为管理员</a-button>

        <a-button @click="batchUnsetManager">取消管理员</a-button>
      </template>
    </a-space>
    <a-table
      bordered
      row-key="id"
      height="50vh"
      :scroll="{
        y: '60vh'
      }"
      :data-source="data"
      :columns="columns"
      :row-selection="rowSelection"
      :pagination="{
      pageSize: query.pageSize,
      current: query.pageNum,
      total: total,
      showTotal: (total: number) => `共${total}条数据`,
      showSizeChanger: true,
      showQuickJumper: true,
      onChange: onPageChanged
    }"
      @resize-column="resizeCallback"
    >
    </a-table>
    <Modal
      v-model:visible="showEdit"
      :title="editUser.id ? '编辑用户' : '新增用户'"
      @ok="onConfirmEdit"
      @cancel="onCancel"
    >
      <Form
        ref="formRef"
        :model="editUser"
        label-align="right"
        :label-col="{
          style: {
            width: '80px'
          }
        }"
        :rules="{
          realName: [
            { required: true, message: '请输入真实姓名', trigger: 'blur' },
            { max: 10, message: '真实姓名不能超过10个字', trigger: 'blur' }
          ],
          userName: [
            { required: true, message: '请输入用户', trigger: 'blur' },
            { min: 6, max: 20, message: '用户账号请输入6-20个字', trigger: 'blur' }
          ],
          password: [
            {
              required: true,
              message: '请输入6-24位的用户密码，包含数字和字母',
              trigger: 'blur',
              min: 6,
              max: 24,
              pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,24}$/
            }
          ]
        }"
      >
        <FormItem label="用户" required name="userName">
          <Input v-model:value="editUser.userName" />
        </FormItem>
        <FormItem label="密码" required name="password">
          <a-input-password v-model:value="editUser.password" type="password" />
        </FormItem>
        <FormItem label="真实姓名" required name="realName">
          <Input v-model:value="editUser.realName" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script lang="tsx" setup>
import { onBeforeMount, ref, watch } from 'vue'
import { page, remove, getDetail, saveOrUpdate, batchRemove } from '@/api/user'
import type { IParam, UserVO } from '@/api/type'
import { USER_COLUMN } from '@/const'
import {
  Form,
  FormItem,
  Input,
  Modal,
  Space,
  type FormInstance,
  type TableProps,
  message
} from 'ant-design-vue'
import type { Key } from 'ant-design-vue/es/table/interface'

const showEdit = ref(false)

const editUser = ref<UserVO>({
  id: '',
  createdTime: '',
  isManager: 0,
  isSuperManager: 0,
  userName: '',
  userId: '',
  realName: '',
  password: '',
  updatedTime: '',
  searchType: 1
})

const rowSelection: TableProps['rowSelection'] = {
  type: 'checkbox',
  onChange(selectedRowKeys: Key[], _selectedRow) {
    console.log(_selectedRow)
    selectedKeys.value = selectedRowKeys.map((o) => o.toString())
  }
}

const formRef = ref<FormInstance>()
function add() {
  showEdit.value = true

  editUser.value = {
    createdTime: '',
    isManager: 0,
    isSuperManager: 0,
    userName: '',
    userId: '',
    realName: '',
    password: '',
    updatedTime: '',
    searchType: 1
  }
}

async function batchRemoveUser() {
  Modal.confirm({
    title: '删除用户',
    content() {
      return '是否删除用户？'
    },
    async onOk() {
      await batchRemove(selectedKeys.value.join(','))
      selectedKeys.value = []
      getDataList()
    }
  })
}

async function batchSetManager() {
  await Promise.all(
    selectedKeys.value.map((o) =>
      saveOrUpdate({
        id: o,
        isManager: 1
      })
    )
  )
  message.success('操作成功')
  getDataList()
}
async function batchUnsetManager() {
  await Promise.all(
    selectedKeys.value.map((o) =>
      saveOrUpdate({
        id: o,
        isManager: 0
      })
    )
  )

  message.success('操作成功')
  getDataList()
}

const edit = async (record: UserVO) => {
  const detail = await getDetail(record.id as string)
  console.log('record', detail)
  editUser.value = detail.data.entity
  showEdit.value = true
}

async function onConfirmEdit() {
  try {
    const result = await formRef.value?.validateFields()
    console.log(result)
    await saveOrUpdate(editUser.value)
    showEdit.value = false
    getDataList()
  } catch (e) {
    console.log(e)
  }
}

const onCancel = () => {
  formRef.value?.clearValidate()
}

const removeUser = (record: UserVO) => {
  // edit
  // remove(record.id)
  Modal.confirm({
    title: '删除用户',
    content: '是否删除用户？',
    onOk() {
      remove(record.id as string).finally(() => getDataList())
    }
  })
}
const columns = ref(
  USER_COLUMN.concat({
    title: '操作',
    dataIndex: 'action',
    width: 200,
    customRender(opt) {
      const record: UserVO = opt.record as UserVO
      if (record.isSuperManager) return <Space />

      return (
        <Space>
          <a class="edit" onClick={() => edit(opt.record)}>
            编辑
          </a>
          <a class="remove" onClick={() => removeUser(opt.record)}>
            删除
          </a>
        </Space>
      )
    }
  })
)

const data = ref<Array<UserVO>>([])

const query = ref<IParam>({
  pageNum: 1,
  pageSize: 20
})

function onPageChanged(page: number, pageSize: number) {
  query.value.pageNum = page
  query.value.pageSize = pageSize
}

const total = ref<number>(0)

const selectedKeys = ref<string[]>([])

const realName = ref('')
const userName = ref('')

const resizeCallback = () => {}
const resetSearch = () => {
  realName.value = ''
  userName.value = ''
  getDataList()
}
const getDataList = async () => {
  try {
    console.log('getDataList', query.value)
    const res = await page({ ...query.value, realName: realName.value, userName: userName.value })
    console.log(res)
    data.value.splice(0)
    if (!res.data?.entity.rows) return
    const respData = res.data.entity
    data.value.push(...respData.rows)
    total.value = respData.total
  } catch (e) {
    console.log(e)
  }
}

const search = () => {
  query.value.pageNum = 1
  getDataList()
}

onBeforeMount(getDataList)

watch(
  query,
  () => {
    console.log('change query')
    getDataList()
  },
  {
    deep: true
  }
)
</script>

<style lang="scss" scoped>
.remove {
  color: red;
}
:deep() {
  .ant-input-password {
    .ant-input-suffix {
      display: none;
    }
  }
}
</style>
